﻿using Deepleo.Weixin.SDK;
using LbangCMS.DBService;
using LbangCMS.EFModels;
using LbangCMS.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Tibus.WeixinWeb;
using LbangCMS.Areas.WeChat.Models;

namespace LbangCMS.Areas.WeChat.Controllers
{
    public class AccountController : Controller
    {
        private IAuthenticationService _authService = new AuthenticationService();
        private MemberService _memberService = new MemberService();

        // GET: WeChat/Account
        public ActionResult Register(int agentId=0)
        {
            var domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];
            var redirect_uri = UrlEncode(string.Format("{0}/Wechat/Account/RegisterCallback", domain));//这里需要完整url地址，对应Controller里面的OAuthController的Callback
            var scope = WeixinConfig.OauthScope;
            var state = agentId.ToString();

            var weixinOAuth2Url = string.Format(
                     "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
                      WeixinConfig.AppID, redirect_uri, scope, state);
            return Redirect(weixinOAuth2Url);
        }

        public ActionResult RegisterCallback(string state,string code="")
        {
            if (!string.IsNullOrEmpty(code))
            {
                int agentId = 0;
                int.TryParse(state, out agentId);
                var access_token_scope = "";
                double expires_in = 0;
                var access_token = "";
                var openId = "";
                var token = OAuth2API.GetAccessToken(code, WeixinConfig.AppID, WeixinConfig.AppSecret);
                dynamic userinfo;

                var refreshAccess_token = OAuth2API.RefreshAccess_token(token.refresh_token, WeixinConfig.AppID);
                access_token = refreshAccess_token.access_token;//通过code换取的是一个特殊的网页授权access_token，与基础支持中的access_token（该access_token用于调用其他接口）不同。
                openId = refreshAccess_token.openid;
                access_token_scope = refreshAccess_token.scope;
                expires_in = refreshAccess_token.expires_in;
                userinfo = OAuth2API.GetUserInfo(access_token, openId);//snsapi_userinfo,可以用户在未关注公众号的情况下获取用户基本信息
                try
                {
                    var model = new RegisterModel()
                    {
                        AgentId = agentId,
                        Avatar = userinfo.headimgurl,
                        NickName = userinfo.nickname,
                        OpenId = openId
                    };
                    return View("Register", model);
                }
                catch (Exception)
                {
                    return RedirectToAction("Register", new { agentId = agentId });
                }
                
                
            }
            else
            {
                return Content("您的微信没有授权，不能进行注册");
                //未授权获取用户信息，不能注册。
            }
        }

        [HttpPost]
        public ActionResult SendRegisterSmsCode(string mobile)
        {
            var member = _memberService.GetMemberByMobile(mobile);
            if (member != null)
            {
                return Json(new { success = false, msg = "手机号码已注册，不能重复注册" });
            }
            string code;
            try
            {
                var saveResult = _memberService.CreateSmsCode(mobile, out code);
                if (saveResult)
                {
                    Alidayu.SendRegisterCode(mobile, code);
                }
                return Json(new { success = true });
            }
            catch
            {

                return Json(new { success = false, msg = "验证码发送失败，请稍后重试" });
            }

        }

        [HttpPost]
        public ActionResult Register(string mobile,string code,string openId,string headimgUrl,string nickName,int agentId)
        {
            var memeber = _memberService.GetMemberByMobile(mobile);
            if (memeber != null)
            {
                return Json(new { success = false, msg = "手机号已注册" });
            }
            else
            {
                var smscode = _memberService.GetLastSmsCode(mobile);
                if (smscode != null && smscode.Code == code)
                {
                    var memberId=_memberService.CreateMember(mobile, nickName, headimgUrl, openId, agentId);
                    _authService.SignIn(memberId.ToString(), nickName, false);
                    return Json(new { success = true, msg = "" });
                }
                else
                {
                    return Json(new { success = false, msg = "短信验证码不正确" });
                }
            }
        }

        public ActionResult Login()
        {
            var domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];
            var redirect_uri = UrlEncode(string.Format("{0}/Account/LoginCallback", domain));//这里需要完整url地址，对应Controller里面的OAuthController的Callback
            var scope = WeixinConfig.OauthScope;
            var state = Guid.NewGuid().ToString().Replace("-","");

            var weixinOAuth2Url = string.Format(
                     "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
                      WeixinConfig.AppID, redirect_uri, scope, state);
            return Redirect(weixinOAuth2Url);
        }

        public ActionResult LoginCallback(string code = "")
        {
            //获取openId,
            //如果openId已存在，直接登录 否则 手动登录
            if (!string.IsNullOrEmpty(code))
            {
                var openId = "";
                var token = OAuth2API.GetAccessToken(code, WeixinConfig.AppID, WeixinConfig.AppSecret);
                var refreshAccess_token = OAuth2API.RefreshAccess_token(token.refresh_token, WeixinConfig.AppID);
                openId = refreshAccess_token.openid;
                var member = _memberService.GetMemberByOpenId(openId);
                if(member!=null)
                {
                    _authService.SignIn(member.Id.ToString(), member.Nick, false);
                    return RedirectToAction("Index", "Member");
                }
            }
            return View("Login");
        }

       

        private string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }

    }
}